package com.xidian.zhiancloud.controller.ledgerManagerment.targetAndSystem;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SecurityWorkPerformanceLedger;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.qo.ledgerManagerment.targetAndSystem.SecurityWorkPerformanceLedgerQO;
import com.xidian.zhiancloud.service.ledgerManager.targerAndSystem.SecurityWorkPerformanceLedgerService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityWorkPerformanceLedgerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 台账管理 目标职责与制度 安全工作绩效台账
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:34
 */
@RestController
@RequestMapping("/SecurityWorkPerformanceLedger")
public class SecurityWorkPerformanceLedgerController extends BaseController {
    @Autowired
    private SecurityWorkPerformanceLedgerService securityWorkPerformanceLedgerService;

    @Autowired
    private OrganizationService organizationService;
    /**
     * 添加安全工作绩效台账对象
     *
     * @param securityWorkPerformanceLedger 安全工作绩效台账对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SecurityWorkPerformanceLedger securityWorkPerformanceLedger) {
        securityWorkPerformanceLedger.setCompanyId(getSessionUserCompanyId());
        securityWorkPerformanceLedger.setCreatorId(getSessionUserid());
        securityWorkPerformanceLedger.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = securityWorkPerformanceLedgerService.save(securityWorkPerformanceLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取安全工作绩效台账对象
     *
     * @param id 安全工作绩效台账对象的id
     * @return 安全工作绩效台账对象
     */
    @GetMapping("/getById")
    public ResultDTO<SecurityWorkPerformanceLedgerVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(securityWorkPerformanceLedgerService.getVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除安全工作绩效台账对象
     *
     * @param ids 安全工作绩效台账对象的id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = securityWorkPerformanceLedgerService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改安全工作绩效台账对象
     *
     * @param securityWorkPerformanceLedger 安全工作绩效台账对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(SecurityWorkPerformanceLedger securityWorkPerformanceLedger) {
        securityWorkPerformanceLedger.setCompanyId(null);
        securityWorkPerformanceLedger.setCreatorId(null);
        securityWorkPerformanceLedger.setCreateTime(null);
        Boolean res = securityWorkPerformanceLedgerService.updateById(securityWorkPerformanceLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param securityWorkPerformanceLedgerQO 查询参数
     * @return 安全工作绩效台账列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<SecurityWorkPerformanceLedgerVO>> getListByQO(SecurityWorkPerformanceLedgerQO securityWorkPerformanceLedgerQO) {
        if (securityWorkPerformanceLedgerQO.getCurrent() == null || securityWorkPerformanceLedgerQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        return ResultDTO.successOf(securityWorkPerformanceLedgerService.selectByQO(securityWorkPerformanceLedgerQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全工作绩效台账导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<SecurityWorkPerformanceLedger> list = securityWorkPerformanceLedgerService.listByIds(Arrays.asList(ids));
        List<SecurityWorkPerformanceLedgerVO> ans = new LinkedList<>();
        list.forEach(t -> {
            SecurityWorkPerformanceLedgerVO vo = new SecurityWorkPerformanceLedgerVO();
            BeanUtils.copyProperties(t, vo);
            Organization organization =organizationService.getById(vo.getAssessedOrganizationId());
            vo.setAssessedOrganizationName(organization==null?"该部门已被删除":organization.getName());
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), SecurityWorkPerformanceLedgerVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<SecurityWorkPerformanceLedgerVO> list = EasyExcel.read(file.getInputStream()).head(SecurityWorkPerformanceLedgerVO.class).sheet().doReadSync();
        List<SecurityWorkPerformanceLedger> ans = new LinkedList<>();
        list.forEach(vo -> {
            SecurityWorkPerformanceLedger ledger = new SecurityWorkPerformanceLedger();
            BeanUtils.copyProperties(vo, ledger);
            ledger.setCreateTime(new Date(System.currentTimeMillis()));
            ledger.setCompanyId(getSessionUserCompanyId());
            ledger.setCreatorId(getSessionUserid());
            LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
            organizationLambdaQueryWrapper.eq(Organization::getName,vo.getAssessedOrganizationName());
            Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
            if(organization!=null){
                ledger.setAssessedOrganizationId(organization.getId());
            }
            ans.add(ledger);
        });
        Boolean res = securityWorkPerformanceLedgerService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
